package jvmtest;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by jianyu.liu@hnlark.com on 2016/6/15.
 *
 * @author jianyu.liu@hnlark.com
 */
public class DeadLock2 {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock1 = new ReentrantLock();
        ReentrantLock lock2 = new ReentrantLock();
        CountDownLatch latch = new CountDownLatch(2);

        new Thread("thread-1"){
            @Override
            public void run() {
                try {
                    lock1.lock();
                    System.out.println(Thread.currentThread().getName()+ "get lock1");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        lock2.lock();
                        System.out.println(Thread.currentThread().getName()+ "get lock2");
                    } finally {
                        lock2.unlock();
                    }
                } finally {
                    lock1.unlock();
                }

                latch.countDown();
            }
        }.start();


        new Thread("thread-2"){
            @Override
            public void run() {
                try {
                    lock2.lock();
                    System.out.println(Thread.currentThread().getName()+ "get lock2");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        lock1.lock();
                        System.out.println(Thread.currentThread().getName()+ "get lock1");
                    } finally {
                        lock1.unlock();
                    }
                } finally {
                    lock2.unlock();
                }

                latch.countDown();
            }
        }.start();

        latch.await();
        System.out.println("test done");

    }
}
